<template>
  <div class="app-container">
    <el-row :gutter="20" class="toolbar" type="flex" justify="space-between">
      <!-- 左侧组合 -->
      <el-col :span="16">
        <el-row :gutter="15">
          <el-col :span="10">
            <el-input
                v-model="searchKey"
                placeholder="输入接口名称搜索"
                @keyup.enter.native="handleSearch">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧按钮 -->
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="handleBindDialog">绑定接口</el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table
        :data="apiList"
        border
        stripe
        style="width: 100%"
        class="data-table">
      <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
      </el-table-column>

      <el-table-column
          prop="name"
          label="接口名称"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="api"
          label="接口路径"
          min-width="200">
      </el-table-column>

      <el-table-column
          prop="createTime"
          label="绑定时间"
          width="180">
      </el-table-column>

      <el-table-column
          prop="creator"
          label="绑定人"
          width="120">
      </el-table-column>

      <el-table-column
          prop="typeName"
          label="鉴权方式"
          width="150">
      </el-table-column>

      <el-table-column
          label="操作"
          width="100"
          align="center">
        <template #default="{row}">
          <el-button
              type="text"
              size="small"
              style="color: #ff4d4f"
              @click="handleDelete(row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 应用详情对话框 -->
    <el-dialog
        title="应用详情"
        :visible.sync="detailDialogVisible"
        width="600px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="应用ID">
          <span>{{ detailData.appId }}</span>
        </el-form-item>
        <el-form-item label="应用名称">
          <span>{{ detailData.appName }}</span>
        </el-form-item>
        <el-form-item label="创建人">
          <span>{{ detailData.creator }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ detailData.createTime }}</span>
        </el-form-item>
        <el-form-item label="密钥">
          <span>{{ detailData.secret || '无' }}</span>
        </el-form-item>
        <el-form-item label="应用描述">
          <span>{{ detailData.remark || '暂无描述' }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 绑定接口地址对话框 -->
    <el-dialog
        ref="bindApiDialog"
        title="绑定接口地址"
        :visible.sync="bindDialogVisible"
        @close="handleDialogClose"
        width="600px">

      <!-- 搜索接口 -->
      <el-input
          v-model="searchApiKey"
          placeholder="搜索接口"
          @keyup.enter.native="handleApiSearch">
        <el-button slot="append" icon="el-icon-search" @click="handleApiSearch"></el-button>
      </el-input>

      <!-- 接口分页列表 -->
      <el-table
          ref="apiTable"
          :data="apiPageList"
          border
          stripe
          style="width: 100%"
          class="data-table">

        <el-table-column
            type="selection"
            width="55">
        </el-table-column>

        <el-table-column
            prop="name"
            label="接口名称"
            min-width="150">
        </el-table-column>

        <el-table-column
            prop="api"
            label="接口地址"
            min-width="200">
        </el-table-column>

        <el-table-column
            label="鉴权类型"
            min-width="150">
          <template #default="{ row }">
            <el-select v-model="row.authType" placeholder="选择鉴权类型">
              <el-option
                  v-for="type in permissionType"
                  :key="type.type"
                  :label="type.name"
                  :value="type.type">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleApiSizeChange"
          @current-change="handleApiCurrentChange"
          :current-page="apiCurrentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="apiPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="apiTotal">
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindSubmit">绑定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {queryGroupApiPage, bindApiPermission, queryPermissionType, delGroupApi} from '@/api/gateway-group'
import {queryApiPage} from '@/api/gateway-api'

export default {
  data() {
    return {
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 新增数据项
      createLoading: false,
      detailDialogVisible: false,
      detailData: {},
      apiList: [],
      bindDialogVisible: false,
      searchApiKey: '',
      apiPageList: [],
      apiCurrentPage: 1,
      apiPageSize: 10,
      apiTotal: 3, // 假设总数为3
      groupId: '',
      permissionType: []
    }
  },
  mounted() {
    this.groupId = this.$route.query.id
    this.loadAppData()
    this.queryPermissionType()
  },
  methods: {
    handleDialogClose(){
      this.searchApiKey = ''
      this.$refs.apiTable.clearSelection()
    },
    async queryPermissionType() {
      const {data} = await queryPermissionType()
      this.permissionType = data
    },
    // 加载数据方法
    async loadAppData() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keywords: this.searchKey,
          groupId: this.groupId,
        }
        const {data} = await queryGroupApiPage(params)
        this.apiList = data.records
        this.total = data.total
        this.currentPage = data.current
        this.pageSize = data.size
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },
    async queryApiPage() {
      const params = {
        page: this.apiCurrentPage,
        size: this.apiPageSize,
        keywords: this.searchApiKey,
        excludeGroupId: this.groupId
      }
      const {data} = await queryApiPage(params)
      this.apiPageList = data.records
      this.apiTotal = data.total
    },
    // 修改后的处理方法
    handleSearch() {
      this.currentPage = 1
      this.loadAppData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadAppData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadAppData()
    },
    // 修改后的创建方法
    handleBindDialog() {
      this.bindDialogVisible = true
      this.queryApiPage()
    },
    handleDelete(row) {
      this.$confirm(`是否删除接口 ${row.name}？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delGroupApi({id: row.id})
          this.$message.success(`删除成功`);
          await this.loadAppData()
        } catch (error) {

        }
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    },
    handleApiSearch() {
      // 实现接口搜索逻辑
      // console.log('搜索接口:', this.searchApiKey);
      this.queryApiPage()
    },
    handleApiSizeChange(val) {
      this.apiPageSize = val;
    },
    handleApiCurrentChange(val) {
      this.apiCurrentPage = val;
    },
    async handleBindSubmit() {
      const selectedRows = this.$refs.apiTable.selection;
      console.log('选中的行:', selectedRows);
      const apiIds = selectedRows.map(item => ({
        apiId: item.id,
        type: item.authType
      }));

      try {
        const response = await bindApiPermission({
          groupId: this.groupId,
          apiId: apiIds // 传入apiIds
        })
        this.$message.success('成功绑定api')
        this.loadAppData()
        this.searchKey = ''
        this.bindDialogVisible = false;
      } catch (error) {
        console.error('绑定失败:', error)
      } finally {
        
      }

    }
  }
}
</script>

<style scoped>

/* 新增样式 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  resize: vertical;
}

.toolbar {
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.data-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.text-right {
  text-align: right;
}

.detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.detail-dialog .el-form-item span {
  font-weight: bold;
  color: #333;
}

.detail-dialog .dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.detail-dialog .el-dialog__body {
  padding: 20px 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>